﻿using CPlatePrintSys.Domain.Events;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Infrastructure;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace CPlatePrintSys.Win.ViewModels
{
    public class LoginWindowViewModel : BindableBase
    {
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;

        public LoginWindowViewModel(IRegionManager regionManager, IUserService userService, IEventAggregator eventAggregator)
        {
            _regionManager = regionManager;
            _eventAggregator = eventAggregator;
        }

        public void HandleLogin(string jsonMessage)
        {
            if (string.IsNullOrEmpty(jsonMessage))
            {
                return;
            }

            // 解析消息 (与之前的 C# 示例相同)
            try
            {
                using (JsonDocument doc = JsonDocument.Parse(jsonMessage))
                {
                    JsonElement root = doc.RootElement;
                    if (root.TryGetProperty("type", out JsonElement typeElement) &&
                        typeElement.GetString() == "LoginSuccess")
                    {
                        
                        _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "MainWindow");
                        _regionManager.RequestNavigate(ConstStrings.UI_Region_Secondary_Content, "HomeView");

                        var accessToken = root.GetProperty("accessToken").GetString();
                        var user = root.GetProperty("user");
                        var userId = user.GetProperty("id").GetString();
                        var userName = user.GetProperty("Username").GetString();
                        var fullName = user.GetProperty("Fullname").GetString();
                        var roles = user.GetProperty("Roles").EnumerateArray().Select(r => r.GetString()).ToList();
                        var userModel = new User();
                        userModel.Username = userName;
                        userModel.FullName = fullName;
                        
                        // 发布用户登录事件
                        _eventAggregator.GetEvent<UserLoggedInEvent>().Publish(new User());
                        // 登录成功后将用户信息保存到App.Current.Properties["CurrentUser"]
                        App.Current.Properties["CurrentUser"] = user;
                        
                    }
                }
            }
            catch (System.Text.Json.JsonException) { /* 忽略无效消息 */ }
        }

        public DelegateCommand LoginCommand { get; }
    }
}
